<script setup lang="ts">
import aiYaoSuKa1 from '@@/assets/images/layouts/ai-word1.png';
import aiYaoSuKa11 from '@@/assets/images/layouts/ai-word-red.png';
import aiYaoSuKa2 from '@@/assets/images/layouts/ai-word2.png';
import aiYaoSuKa21 from '@@/assets/images/layouts/ai-word21.png';
import aiYaoSuKa3 from '@@/assets/images/layouts/ai-word3.png';
import aiYaoSuKa31 from '@@/assets/images/layouts/ai-word31.png';
import type { FormRules } from "element-plus"
import { loginApi } from "../login/apis"
import {LoginRequestData} from "@/pages/login/apis/type.js"
import logoUrl0 from '@@/assets/images/layouts/logo.png';
import Header from "@@/components/Head/index.vue"
import { getCardDetailListApi, sendCommentApi, getUserInfoApi } from "@/api"
import { useUserStore } from "@/pinia/stores/user.js"
import { onBeforeMount, onMounted, ref } from "vue"
import {removeToken} from "@@/utils/cache/cookies";
import goToBottom from "@@/assets/images/layouts/go_to_bottom.png";
const userStore = useUserStore()
const dialogVisible = ref(false)
const freeUserDialogVisible = ref(false)
const router = useRouter()
const checked = ref(true)
const commentDialog = ref(false)
const token = ref("")
const commentForm = ref('')
const commentFormRef = useTemplateRef("commentFormRef")
const formSendData = ref({
  id: null
})
const formDialog = ref(true)
const formWechatDialog = ref(false)
const scrollContainer = ref(null);
const go_to_bottom_show = ref(true)
const list = ref([]) // 10条AI推荐列表数据
const username = ref("")
const userInfo = ref({})
const iframeUrl = ref("https://www.sacasaca.com/wechatloginqrocde.html")
/** 登录按钮 Loading */
const loading = ref(false)
/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  account: [
    { required: true, message: "请输入用户名/账号", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" }
  ],
  code: [
  ]
}
const styleWechat = ref('width:80%; margin: 0 auto')
/** 登录表单元素的引用 */
const loginFormRef = useTemplateRef("loginFormRef")
/** 登录表单数据 */
const loginFormData: LoginRequestData = reactive({
  username: "",
  account: "",
  password: "",
  mobile: "",
  code: ""
})
onBeforeMount(() => {
  let currentDomain = window.location.hostname;
  if (currentDomain === 'sacasaca.com') {
    location.href='https://www.sacasaca.com/#/ai';
  }
  // 组件已完成响应式状态设置，但未创建DOM节点
  username.value = userStore.getUserName().value
  token.value = userStore.token
  if (token.value === '') {
    dialogVisible.value = true
  }
  getCardDetailList()
  getUserInfoApi({ uid: userStore.getUserId().value }).then(({code, data}) => {
    userInfo.value = data
    console.log(data)
  })
  checkUserIsVip()
})
function buyVip () {
  router.push({
    path: '/quanyi'
  })
}
function showFreeUser() {
  freeUserDialogVisible.value = true
}
function showCommentDialog( id: string | undefined ) {
  formSendData.value.id = id
  console.log(formSendData.value.id )
  commentDialog.value = true
}
// cancelComment
function cancelComment() {
  commentForm.value =  ""
  commentDialog.value = false
}
function handleComment() {
  if (commentForm.value !== "") {
    const data2 = {
      source_id: formSendData.value.id,
      contents: commentForm.value,
      // user_id: parseInt(userStore.getUserId()),
      user_id: userStore.getUserId().value,
      ctype: 1,
      img_list: ""
    }
    sendCommentApi(data2).then((data) => {
      commentDialog.value = false
      commentForm.value =  ""
      ElMessage.success({
        message: "评论成功",
        type: "success",
        duration: 2000
      })
    })
  } else {
    ElMessage.error({
      message: "请输入评论内容",
      type: "warning",
      duration: 2000
    })
  }

}
/** 登录 */
function handleLogin() {
  loginFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    loginFormData.username = loginFormData.account
    loginFormData.mobile = loginFormData.account
    loading.value = true
    loginApi(loginFormData).then(({ data }) => {
      userStore.setUsername(loginFormData.account) // token-admin
      userStore.setToken(data.token) // token-admin
      userStore.setUserId(data.id) // token-admin
      dialogVisible.value = false
    }).catch(() => {
      ElMessage.error({
        message: "验证失败",
        type: "warning",
        duration: 2000
      })
      // loginFormData.password = ""
    }).finally(() => {
      loading.value = false
    })
  })
}
function logout() {
  token.value = ""
  username.value = ""
  removeToken()
  userStore.setToken("") // token-admin
  userStore.setUsername("")
}
function goStudyUrl(id) {
  router.push({
    path: '/ai-detail',
    params: {
      id: id
    }
  })
}
function resetForm () {
  // refs["formLogin"].resetFields()
}
function goToUrl (type, param) {
  if (param) {
    router.push({
      name: 'aiAsk',
      params: {
        id: param
      }
    })
  } else {
    router.push({
      path: type
    })
  }
}
function showWechatForm (param) {
  if (param === 1) {
    formDialog.value = true
    formWechatDialog.value = false
    styleWechat.value = 'width:80%; margin: 0 auto'
  } else {
    formDialog.value = false
    formWechatDialog.value = true
    styleWechat.value = 'width:60%; margin: 0 auto'
  }

}
function getCardDetailList() {
  const data2 = { page: 1, type: "1", limit: 10 }
  getCardDetailListApi(data2).then(({ data: tableData }) => {
    // console.log(tableData)
    // list.value = tableData
    for (let i = 0; i < tableData.length; i++) {
      list.value.push({
        id: tableData[i].id,
        title: tableData[i].title,
        description: tableData[i].description,
        create_time: tableData[i].create_time,
        source_author: tableData[i].source_author,
        content: tableData[i].content
      })
    }
    console.log(list)
  }).catch((data) => {
    console.log(data)
  }).finally(() => {
    loading.value = false
  })
}
function scrollToBottom () {
  // console.log(scrollContainer.value.scrollHeight)
  if (scrollContainer.value) {
    scrollContainer.value.scrollTo({
      top: scrollContainer.value.scrollHeight, // 滚动到最底部
      behavior: 'smooth' // 平滑滚动效果（如果需要的话）
    });
  }
}
const handleScroll = () => {
  const scrollTop = scrollContainer.value.scrollTop;
  const scrollHeight = scrollContainer.value.scrollHeight;
  // console.log(scrollTop)
  // console.log(scrollHeight)
  if (scrollTop >= (scrollHeight - 830)) {
    go_to_bottom_show.value = false
  } else {
    go_to_bottom_show.value = true
  }
};
function onIframeLoad() {
  // iframe加载完成后的处理
  const iframe = document.getElementById('searchshow');
  if (!iframe) return;

  // 设置默认高度，根据用户偏好使用100vh而不是固定像素值
  // iframe.style.height = '100vh';

  // 设置消息监听器
  setupMessageListener();
}
// 使用消息机制来处理iframe高度
function setupMessageListener()
{
  // 先移除可能存在的旧监听器，避免重复添加
  removeMessageListener();
  // 添加消息事件监听器
  window.addEventListener('message', handleIframeMessage);
  console.log('已设置消息监听器');
}
function removeMessageListener() {
  // 移除消息事件监听器
  window.removeEventListener('message', handleIframeMessage);
  console.log('已移除消息监听器');
}
function handleIframeMessage(event) {
  if (event.data && typeof event.data === 'object' && event.data.type === 'resize') {
    const iframe = document.getElementById('searchshow');
    if (iframe && event.data.height) {
      iframe.style.height = `${event.data.height}px`;
      console.log(`收到高度更新: ${event.data.height}px, 视图模式: ${event.data.viewMode || '未指定'}`);
    }
  }
}
function checkUserIsVip() {
  // 定时器检查接口getUserInfoApi, 如果返回值是1，则显示弹出框 。
  const timer = setTimeout(() => {
    getUserInfoApi({ uid: userStore.getUserId().value }).then(({code, data}) => {
      console.log(data)
      if (data.is_vip === 0) {
        freeUserDialogVisible.value = true
      }
      clearInterval(timer)
    })
  }, 5000)
}
</script>

<template>
  <!-- login-container的高度是屏幕的最大距离 -->
  <div class="login-container" style="display: flex;flex-direction: column;height: 100vh;">

    <Header :activeId="1" />
    <el-dialog v-model="commentDialog" :width="550" title="评论">
      <el-form ref="commentFormRef" label-width="80">
        <el-form-item label="评论内容">
          <el-input type="textarea" :rows="3" resize='none' autocomplete="off"  v-model="commentForm" placeholder="请输入评论内容"></el-input>
        </el-form-item>
        <el-form-item>
          <div style="display: flex;flex-direction: row;justify-content: center;">
            <el-button type="primary" @click="handleComment()">提交</el-button>
            <el-button type="default" @click="cancelComment()">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 登录界面 -->
    <el-dialog v-model="dialogVisible" title="" :width="550" @closed="resetForm" :close-on-click-modal="false">
      <div :style="styleWechat">
        <div class="title-left">
          <div class="icon icon1" style="height: 10px; width: 60px;" />
          <div class="title" @click="showWechatForm(1)">
            账号登录
          </div>
          <div class="title" style="margin-left: 10px;" @click="showWechatForm(2)">
            微信登录
          </div>
        </div>
        <el-form v-show="formDialog" :model="loginFormData" ref="loginFormRef" label-position="left" :rules="loginFormRules" label-width="80px">
          <el-form-item label="用户名" class="username2" prop="account">
            <el-input size="large" autocomplete="off" v-model="loginFormData.account" placeholder="请输入用户名/手机号"  />
            <template #error>
              <div class="custom-error">请输入用户名/手机号</div>
            </template>
          </el-form-item>
          <el-form-item label="密码" class="password2" prop="password">
            <el-input size="large" autocomplete="off" v-model="loginFormData.password" type="password" placeholder="请输入密码" />
            <template #error>
              <div class="custom-error">请输入六位以上的密码</div>
            </template>
          </el-form-item>
        </el-form>
        <div v-show="formWechatDialog" style="height: 400px;width:500px;overflow: hidden;">
          <iframe :src="iframeUrl" id="searchshow" frameborder="0" style="width: 350px; height: 550px;overflow: hidden; " scroll="no" ref="iframeRef" @load="onIframeLoad"></iframe>
        </div>
      </div>
      <template #footer>
        <div style="display: flex;justify-content: center;" v-show="formDialog">
          <el-button size="large" style="width:100px;" @click="dialogVisible = false">
            取消
          </el-button>
          <el-button size="large" style="width:100px;" type="primary" @click="handleLogin">
            确认
          </el-button>
        </div>
        <div style="display: flex;justify-content: center;" v-show="formDialog">
          <div style="width: 120px; margin-right: 10px;line-height: 40px">
            没有账号？<a href="/#/register" class="register">注册</a>
          </div>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="freeUserDialogVisible" title="用户信息"  class="custom-dialog" center top="14vh" :close-on-click-modal="false"
               :close-on-press-escape="true"
               append-to-body :width="650" @closed="resetForm" >
      <div :style="styleWechat">
        <div class="title-left">
          <div class="icon icon1" style="height: 10px; width: 60px;" />
          <div class="title">
            <div style="display: flex;flex-direction: column;">
              <div style="font-size: 14px;color: #0e2442;">您是saca体验用户, 90天后到期，<el-button type="primary" @click="buyVip()">购买正式会员</el-button></div>
              <div style="font-size: 12px;color: #0E6EF6;">购买正式会员可获得更多功能,到期时间是 {{userInfo.expire_time}}</div>
            </div>
          </div>
        </div>
        <div style="width: 100%;height: 330px;display: flex;flex-direction: column;">
          <div style="width: 100%;height: 330px;display: flex;flex-direction: row;">
            <div style="width: 46%;height: 130px;padding: 10px;">
              用户权益1用户权益1用户权益1用户权益1
            </div>
            <div style="width: 46%;height: 130px;padding: 10px;">
              用户权益3用户权益3用户权益3用户权益3
            </div>
          </div>
          <div style="width: 100%;height: 130px;display: flex;flex-direction: row;">
            <div style="width: 46%;height: 130px;padding: 10px;">
              用户权益2用户权益2用户权益2用户权益2
            </div>
            <div style="width: 46%;height: 130px;padding: 10px;">
              用户权益4用户权益4用户权益4用户权益4
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div style="display: flex;justify-content: center;" >
          <el-button size="default" style="width:80px;margin-bottom: 10px;" @click="freeUserDialogVisible = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
    <div class="ai w-1200" element-loading-text="Loading...">
      <div class="ai-left">
        <div class="ai-left-tool">
          <div class="ai-left-tool-item selected">
            <div class="icon icon1 iconSelected" style="height: 31px; width: 31px;" />
            <div class="title titleSelected" @click="goToUrl('/ai', false)">
              推荐
            </div>
          </div>
          <div class="ai-left-tool-item">
            <div class="icon icon2" style="height: 30px; width: 30px;"  @click="goToUrl('/ai2', false)"/>
            <div class="title" @click="goToUrl('/ai2', false)">
              问答
            </div>
          </div>
          <div class="ai-left-tool-item">
            <div class="icon icon3" style="height: 32px; width: 30px;"  @click="goToUrl('/ai3', false)"/>
            <div class="title" @click="goToUrl('/ai3', false)"> 学习 </div>
          </div>
          <div class="ai-left-tool-item">
            <div class="icon icon5" style="height: 30px; width: 30px;" />
            <div class="title"> 专业工具 </div>
          </div>
          <div class="ai-left-tool-item">
            <div class="icon icon6" style="height: 30px; width: 30px;"  @click="goToUrl('/ai4', false)"/>
            <div class="title" @click="goToUrl('/ai4', false)"> 记录 </div>
          </div>
          <div class="ai-left-tool-item">
            <div class="icon icon7" style="height: 30px; width: 30px;"  @click="goToUrl('/ai2', false)"/>
            <div class="title" @click="goToUrl('/ai5', false)"> 指南 </div>
          </div>
        </div>
      </div>

      <div class="ai-right scroll" ref="scrollContainer" @scroll="handleScroll" >
        <div style="width: 892px;">
          <div class="question-box">
            <div class="item" @click="goToUrl('/ai2', '有什么热门美白成分？')">
              有什么热门美白成分？
            </div>
            <div class="item" @click="goToUrl('/ai2', '现在最火的抗老成分是啥？除了A醇、玻色因，有没有新出来的、效果猛又不容易翻车的？')">
              现在最火的抗老成分是啥？
            </div>
            <div class="item" @click="goToUrl('/ai2', '在朋友圈发的宣传算广告吗，是否需要按照化妆品的要求及相关法律法规来了？')">
              在朋友圈发
            </div>
            <div class="item" @click="goToUrl('/ai2', '在朋友圈发的宣传算广告吗，是否需要按照化妆品的要求及相关法律法规来了？')">
              在朋友圈发
            </div>
            <div class="item" @click="goToUrl('/ai2', '在朋友圈发的宣传算广告吗，是否需要按照化妆品的要求及相关法律法规来了？')">
              在朋友圈发
            </div>
            <div class="item" @click="goToUrl('/ai2', '在朋友圈发的宣传算广告吗，是否需要按照化妆品的要求及相关法律法规来了？')">
              在朋友圈发
            </div>
            <div class="item" @click="goToUrl('/ai2', '在朋友圈发的宣传算广告吗，是否需要按照化妆品的要求及相关法律法规来了？')">
              在朋友圈
            </div>
            <div class="item" @click="goToUrl('/ai2', '在朋友圈发的宣传算广告吗，是否需要按照化妆品的要求及相关法律法规来了？')">
              在朋友圈发的
            </div>
            <div class="item" @click="goToUrl('/ai2', '在朋友圈发的宣传算广告吗，是否需要按照化妆品的要求及相关法律法规来了？')">
              在朋友圈发
            </div>
            <div class="item" @click="goToUrl('/ai2', '美国产品CI 77891  作为着色剂也要变成TITANIUM DIOXIDE吗 不能标注CI号')">美国产品</div>
          </div>
          <div class="ysk-box" v-for="item in list" :key="item.id">
            <div class="top">
              <div class="left">
                <div class="text1 active1" @click="showFreeUser()">
                  政策
                </div>
                <div class="text1">
                  资讯
                </div>
                <div class="text1">
                  文献
                </div>
                <div class="text1">
                  数据
                </div>
                <div class="text1">
                  课件
                </div>
                <div class="text1">
                  其他
                </div>
              </div>
              <div class="right">
                <div class="right-item">
                  <div class="imgKa"><img :src="aiYaoSuKa1" class="img1" /></div>
                  <div class="text2">摘要卡</div>
                </div>
                <div class="right-item">
                  <div class="imgKa"><img :src="aiYaoSuKa2" class="img1" /></div>
                  <div class="text2">应询卡</div>
                </div>
                <div class="right-item">
                  <div class="imgKa"><img :src="aiYaoSuKa31" class="img1" /></div>
                  <div class="text2-blue">要素卡</div>
                </div>
              </div>
            </div>

            <div class="center1">
              <div class="left">
                <div class="row1">
                  <router-link :to="{ name: 'yasukaDetail', params: { id: item.id } }" target="_blank">
                  {{item.title}}
                  </router-link>
                </div>
                <div class="row2 text1">
                  {{item.source_author}}
                </div>
                <div class="row3 text1" style="display: flex;flex-direction: row;justify-content:space-between;">
                  <div>{{item.create_time.replace('-','.').replace('-','.').substring(0,16)}}</div>
                </div>
              </div>
              <div class="right">
                <div class="row1">
                  摘要：
                </div>
                <div class="row2">
                  <div class="text5"> {{item.content.substring(0, 280)}}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div style="height: 30px;width:100%;display: flex;flex-direction: column;position: fixed;top: calc(100% - 88px );left: 10%;">
          <div class="go_to_bottom"  @click="scrollToBottom" v-show="go_to_bottom_show">
            <el-image :src="goToBottom" style="width:40px;height:40px;" alt="" width="40" height="40"></el-image>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style src="@/pages/ai/style/index.css"  scoped></style>
<style lang="scss" scoped>
.go_to_bottom {
  border-radius: 16px;
  cursor: pointer;
  position: relative;
  margin: 0 auto;
  transform: translateX(-50%);
  width: 40px;
  height: 40px;
  color: #ffffff;
  text-align: center;
  padding: 0;
  background-color: #ffffffff;
  z-index: 19;
}
.custom-dialog {
  border-radius: 8px;
}
</style>
<style lang="scss">
:root {
  --el-dialog-border-radius: 8px !important;
  --el-border-radius-base: 8px !important;
}
</style>
